var express = require("express");
const { append } = require("express/lib/response");
var r = express.Router();
//引入第三方图形验证码模块
const svgCaptcha = require("svg-captcha");

//引入数据库连接模块
const pool = require("../pool.js");

// 引入MD5模块
const MD5 = require("MD5");

//用户注册验证码
//所有图形验证，服务器node一个程序出生一张图
//验证码接口(get /reg)
//接口的地址：http://127.0.0.1:3000/v1/code

r.get("/code", (req, res) => {
  const cap = svgCaptcha.createMathExpr({
    fontSize: 45, //字体大小
    mathMin: 1, //参与运算数字最小和最大9
    mathMax: 9, //10以内运行
    mathOperator: "+-", //运算符 加法减法
    window: 110, //宽度高度
    height: 45,
    color: true, //是否彩色
  });
  // req.session.captcha = cap.text; //session存储验证码数值1+5=正确答案6
  global.captcha = cap.text;
  // console.log(global.captcha);
  res.type("svg"); //修改服务器响应的类型
  res.send(cap.data);
  // console.log(req.session.captcha);
});

//1.登录模块
//http://127.0.0.1:3000/v1/login
r.post("/login", (req, res) => {
  //获取用户输入验证码
  // var code = req.body.code;
  // console.log(req.body.uname.length);
  let _uname = req.body.uname;
  let _upwd = req.body.upwd;

  //判断用户输入的是否是手机号
  let sql;
  if (req.body.uname.length == 11) {
    sql = "select * from j_user where uphone=? and upwd=MD5(?)";
  } else {
    sql = "select * from j_user where uname=? and upwd=MD5(?)";
  }
  // console.log(sql);
  pool.query(sql, [_uname, _upwd], (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      req.session.auth = true; //登录凭证
      res.send({ code: 200, msg: "登录成功" });
    } else {
      req.session.auth = false;
      res.send({ code: 404, msg: "登录失败,用户名或者密码错误" });
    }
  });
});
// ---------
//验证码验证
r.get("/verifyCaptcha", function (req, res) {
  // console.log(global.captcha);
  // console.log("验证码:", req.query, req.session.captcha);
  // console.log(req.session);
  // console.log(req.query.yzm);
  if (req.query.yzm == global.captcha) {
    res.json({
      msg: "验证码是对的",
      code: 200,
    });
  } else {
    res.json({
      msg: "验证码错误",
      code: 404,
    });
  }
});
// ------------

//用户注册接口(post /reg)
//接口的地址：http://127.0.0.1:3000/v1/register
//接口的请求方式:post
r.post("/register", (req, res, next) => {
  //1.1获取post传递的参数
  var obj = req.body;
  // console.log(obj);
  //1.2执行SQL命令,将数据插入到数据库
  // MD5 数据加密 但需要引入模块
  //console.log(r)
  pool.query(
    "insert j_user(uname,upwd,uemail,uphone) values(?,MD5(?),?,?)",
    [obj.uname, obj.upwd, obj.uemail, obj.uphone],
    (err, r) => {
      if (err) {
        //抛出错误，阻止后边程序的执行，用于调试
        //throw err;
        //交给下一个错误处理中间件同时把错误信息传递过去
        next(err);
        //阻止往后执行
        return;
      }
      //console.log(r);
      if (r.affectedRows == 1) {
        res.send({ code: 200, msg: "注册成功" });
      } else {
        res.send({ code: 404, msg: "注册失败" });
      }
    }
  );
});

// 还未验证
//2.查询用户列表--分页查询
//接口的地址：http://127.0.0.1:3000/v1/list
r.get("/list", (req, res) => {
  //(1)拦截非法操作 没有登录查看用户列表
  //
  if (!req.session.auth) {
    //登录凭证不存在
    res.send({ code: 0, msg: "未登录" });
    return;
  }

  //2分页查询
  //(1)方便用户使用
  //(2)降低系统压力
  var page = parseInt(req.query.page); //页码 1 2 3 4 ...
  var pageSize = 3; //一页几行
  if (!page) {
    page = 1; //默认第一页
  }
  //3:查询当前页内容
  var sql = "select * from xz_user limit ?,?";
  var offset = (page - 1) * pageSize;
  pool.query(sql, [offset, pageSize], (err, result1) => {
    if (err) throw err;
    //查询总页数  4
    var sql = "select count(uid) as c from xz_user";
    pool.query(sql, (err, result2) => {
      if (err) throw err;
      var count = Math.ceil(result2[0].c / pageSize); //1.25 =>2
      //                          当前页内容     总页数      当前页码
      res.send({
        code: 1,
        msg: "成功",
        data: result1,
        total: count,
        pageNo: page,
      });
    });
  });
});

// 轮播图接口
//接口地址：http://127.0.0.1:3000/v1/slideshow
r.get("/slideshow", (req, res, next) => {
  pool.query("select * from  j_index_carousel1", (err, r) => {
    if (err) {
      next(err);
      return;
    }
    //如果没有错误，响应给前端
    res.send({ code: 200, msg: "查询成功", data: r });
  });
});

// 上传文件
//接收请求
//配置multer中间件
const multer = require("multer");
obj = multer.diskStorage({
  destination: function (req, file, cb) {
    //指定目录
    cb(null, "public/img/index_slideshow");
  },
  filename: function (req, file, cb) {
    // 指定文件名
    let name = file.originalname;
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf("."));
    cb(null, uuid.v4() + ext);
  },
});
const uploadTools = multer({
  storage: obj,
});
const uuid = require("uuid");
r.post("/upslide", uploadTools.array("uploadFile"), (req, res) => {
  // console.log(req.files);
  let urls = [];
  req.files.forEach((item) => {
    urls.push(`http://127.0.0.1:3000/${item.filename}`);
    global.filename = "img/index_slideshow/" + item.filename;
    // console.log("测试", global.filename);
  });
  res.send({ code: 200, msg: "ok", urls: urls });
});

//上传轮播图
r.post("/slideshow", (req, res, next) => {
  //1.1获取post传递的参数
  var obj = req.body;
  // console.log(obj);
  //1.2执行SQL命令,将数据插入到数据库
  // MD5 数据加密 但需要引入模块
  //console.log(r)
  // console.log(global.filename);
  pool.query(
    "insert j_index_carousel1(jid,comname,img,detail) values(?,?,?,?)",
    [obj.jid, obj.comname, global.filename, obj.detail],
    (err, r) => {
      if (err) {
        //抛出错误，阻止后边程序的执行，用于调试
        //throw err;
        //交给下一个错误处理中间件同时把错误信息传递过去
        next(err);
        //阻止往后执行
        return;
      }
      // console.log(r);
      if (r.affectedRows == 1) {
        res.send({ code: 200, msg: "上传成功" });
      } else {
        res.send({ code: 404, msg: "上传失败" });
      }
    }
  );
});

//.根据jid删除轮播图
r.delete("/delslideshow", (req, res) => {
  // console.log(req);
  var _jid = req.query.jid;
  var sql = "delete from j_index_carousel1 where jid=?";
  pool.query(sql, [_jid], (err, r) => {
    if (err) throw err;
    // console.log(r);
    if (r.affectedRows > 0) {
      res.send({ code: 200, msg: "删除成功" });
    } else {
      res.send({ code: 404, msg: "删除失败" });
    }
  });
});

module.exports = r;
